<template>
  <a-modal :open="open" title="提取的数据" width="1200px" :footer="null" @cancel="handleCancel" :maskClosable="false" @after-close="handleAfterClose">
    <div class="extracted-data-container">
      <div class="table-actions" style="margin-bottom: 16px;">
        <a-button type="primary" @click="showDataDisplayModal" :disabled="selectedRows.length === 0">
          提取PMS数据
        </a-button>
        <a-button type="primary" danger @click="deleteSelectedRows" :disabled="selectedRows.length === 0" style="margin-left: 8px;">
          删除选中数据
        </a-button>
        <a-button type="primary" @click="showUseFormSchemasModal" :disabled="selectedRows.length === 0" style="margin-left: 8px;">
          useForm Schemas
        </a-button>
        <a-button type="primary" @click="showUseTableColumnsModal" :disabled="selectedRows.length === 0" style="margin-left: 8px;">
          useTable Columns
        </a-button>
      </div>

      <vxe-table 
        ref="tableRef" 
        :data="tableData" 
        :checkbox-config="{ reserve: true }" 
        :row-config="{ keyField: 'key' }"
        :tree-config="{ indent: 20, expandAll: true }"
        @checkbox-change="handleSelectionChange" 
        @checkbox-all="handleSelectionChange"
        height="400">
        <vxe-column type="checkbox" width="50"></vxe-column>
        <vxe-column field="value" title="字段名">
          <template #default="{ row }">
            <span 
              class="param-name-cell" 
              :style="{ paddingLeft: row.level * 20 + 'px', fontWeight: '500' }"
            >
              {{ row.value }}
            </span>
          </template>
        </vxe-column>
        <vxe-column field="componentType" title="字段类型" width="220">
          <template #default="{ row }">
            <a-select 
              v-model:value="row.componentType" 
              :options="componentTypeOptions" 
              placeholder="请选择字段类型" 
              @change="onComponentTypeChange(row)"
              style="width: 140px;">
            </a-select>
          </template>
        </vxe-column>
        <vxe-column field="label" title="描述" >
          <template #default="{ row }">
            <span class="param-name-cell" :style="{ paddingLeft: row.level * 20 + 'px' }">{{ row.label }}</span>
          </template>
        </vxe-column>
        <vxe-column title="操作" width="180">
          <template #default="{ row }">
            <a-button type="link" @click="showComponentConfigModal(row)">配置</a-button>
            <a-button type="link" danger @click="deleteRow(row)">删除</a-button>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </a-modal>

  <!-- 组件配置模态框 -->
  <a-modal
    v-model:open="componentConfigModalVisible"
    :title="`${currentEditingRow?.componentType || ''} 组件配置`"
    @ok="confirmComponentConfig"
    @cancel="cancelComponentConfig"
    width="600px"
  >
    <div v-if="currentEditingRow">
      <!-- ParamSelect 类型配置 -->
      <div v-if="currentEditingRow.componentType === 'ParamSelect'">
        <a-form layout="vertical">
          <a-form-item label="Kind 值">
            <a-input v-model:value.trim="currentEditingRow.kind" placeholder="请输入kind值" />
          </a-form-item>
          <a-form-item label="禁用">
            <a-switch v-model:checked="currentEditingRow.disabled" />
          </a-form-item>
          <a-form-item label="可清空">
            <a-switch v-model:checked="currentEditingRow.allowClear" />
          </a-form-item>
        </a-form>
      </div>
      
      <!-- Select 类型配置 -->
      <div v-else-if="currentEditingRow.componentType === 'Select'">
        <a-form layout="vertical">
          <a-form-item label="禁用">
            <a-switch v-model:checked="currentEditingRow.disabled" />
          </a-form-item>
          <a-form-item label="可清空">
            <a-switch v-model:checked="currentEditingRow.allowClear" />
          </a-form-item>
        </a-form>
      </div>
      
      <!-- DatePicker 类型配置 -->
      <div v-else-if="currentEditingRow.componentType === 'DatePicker'">
        <a-form layout="vertical">
          <a-form-item label="日期格式">
            <a-input v-model:value="currentEditingRow.valueFormat" placeholder="例如: YYYY-MM-DD" />
          </a-form-item>
          <a-form-item label="禁用">
            <a-switch v-model:checked="currentEditingRow.disabled" />
          </a-form-item>
          <a-form-item label="可清空">
            <a-switch v-model:checked="currentEditingRow.allowClear" />
          </a-form-item>
        </a-form>
      </div>
      
      <!-- Input 类型配置 -->
      <div v-else-if="currentEditingRow.componentType === 'Input'">
        <a-form layout="vertical">
          <a-form-item label="禁用">
            <a-switch v-model:checked="currentEditingRow.disabled" />
          </a-form-item>
          <a-form-item label="可清空">
            <a-switch v-model:checked="currentEditingRow.allowClear" />
          </a-form-item>
        </a-form>
      </div>
      
      <!-- 其他类型 -->
      <div v-else>
        <a-empty description="该组件类型暂无特殊配置项" />
      </div>
    </div>
  </a-modal>

  <!-- 数据展示模态框 -->
  <DataDisplayModal :open="dataDisplayModalVisible" :data="selectedData"
    @update:open="dataDisplayModalVisible = $event" />
  
  <!-- UseForm Schemas 格式展示模态框 -->
  <UseFormSchemasModal 
    :open="useFormSchemasModalVisible" 
    :data="selectedData"
    @update:open="useFormSchemasModalVisible = $event" />
  
  <!-- UseTable Columns 格式展示模态框 -->
  <UseTableColumnsModal 
    :open="useTableColumnsModalVisible" 
    :data="selectedData"
    @update:open="useTableColumnsModalVisible = $event" />
</template>

<script setup>
import { ref, computed, nextTick, watch } from 'vue'
import DataDisplayModal from './DataDisplayModal.vue'
import UseFormSchemasModal from './UseFormSchemasModal.vue'
import UseTableColumnsModal from './UseTableColumnsModal.vue'

const props = defineProps({
  open: {
    type: Boolean,
    required: true
  },
  data: {
    type: Array,
    default: () => []
  }
})


watch(() => props.open, (newOpen) => { 
  if (newOpen) {
    // 弹框打开时清空选择
    selectedRows.value = []
    nextTick(() => {
      if (tableRef.value) {
        tableRef.value.clearCheckboxRow()
        tableRef.value.clearCheckboxReserve()
      }
    })
  }
})

const emit = defineEmits(['update:open'])
// 组件类型选项
const componentTypeOptions = [
  { label: 'Input', value: 'Input' },
  { label: 'ParamSelect', value: 'ParamSelect' },
  { label: 'Select', value: 'Select' },
  { label: 'DatePicker', value: 'DatePicker' },
]
// 表格引用
const tableRef = ref()

// 选中行数据
const selectedRows = ref([])

// 模态框控制
const dataDisplayModalVisible = ref(false)
const useFormSchemasModalVisible = ref(false)
const useTableColumnsModalVisible = ref(false)
const componentConfigModalVisible = ref(false)
const selectedData = ref([])

// 组件配置相关
const currentEditingRow = ref(null)
const tempSelectOptions = ref([]) // 临时存储Select选项，确认时再更新到currentEditingRow

// 内部数据状态
const internalData = ref([])

// 监听props.data变化，更新内部数据状态
watch(() => props.data, (newData) => {
  internalData.value = [...newData.map(item=>{
    return {
      ...item,
      componentType: item.componentType || 'Input',
      kind: item.kind || '', // ParamSelect的kind属性
      valueFormat: item.valueFormat || 'YYYY-MM-DD', // DatePicker的格式
      allowClear: item.allowClear || false, // 可清空属性
      disabled: item.disabled || false, // 禁用属性
      options: item.options || [] // Select的选项
    }
  })]
}, { immediate: true })

// 表格数据，添加层级信息
const tableData = computed(() => {
  return internalData.value.map(item => ({
    ...item,
    level: item.level || 0
  }))
})

const handleCancel = () => {
  emit('update:open', false)
}

const handleAfterClose = () => {
  // 弹框完全关闭后清空选中状态
  selectedRows.value = []
  nextTick(() => {
    if (tableRef.value) {
      tableRef.value.clearCheckboxRow()
      tableRef.value.clearCheckboxReserve()
    }
  })
}

const handleSelectionChange = ({ records }) => {
  selectedRows.value = records
}

const showDataDisplayModal = () => {
  // 只提取当前选中的数据
  selectedData.value = [...selectedRows.value]
  dataDisplayModalVisible.value = true
}

const showUseFormSchemasModal = () => {
  selectedData.value = [...selectedRows.value]
  useFormSchemasModalVisible.value = true
}

const showUseTableColumnsModal = () => {
  selectedData.value = [...selectedRows.value]
  useTableColumnsModalVisible.value = true
}

// 删除选中行
const deleteSelectedRows = () => {
  const selectedKeys = selectedRows.value.map(row => row.value)
  // 创建新的数组实例以确保响应式更新
  internalData.value = internalData.value.filter(item => !selectedKeys.includes(item.value))
  
  // 清空选择
  selectedRows.value = []
  nextTick(() => {
    if (tableRef.value) {
      tableRef.value.clearCheckboxRow()
      tableRef.value.clearCheckboxReserve()
    }
  })
}

// 删除单行
const deleteRow = (row) => {
  // 创建新的数组实例以确保响应式更新
  internalData.value = internalData.value.filter(item => item.value !== row.value)
  
  // 从选中列表中移除（如果已被选中）
  const index = selectedRows.value.findIndex(item => item.value === row.value)
  if (index > -1) {
    selectedRows.value.splice(index, 1)
  }
  
  nextTick(() => {
    if (tableRef.value) {
      tableRef.value.clearCheckboxRow()
      tableRef.value.clearCheckboxReserve()
    }
  })
}

// 字段类型改变处理函数
const onComponentTypeChange = (row) => {
  // 确保切换类型后相关属性存在
  switch (row.componentType) {
    case 'ParamSelect':
      row.kind = row.kind || '';
      row.disabled = row.disabled || false;
      row.allowClear = row.allowClear || false;
      break;
    case 'DatePicker':
      row.valueFormat = row.valueFormat || 'YYYY-MM-DD';
      row.disabled = row.disabled || false;
      row.allowClear = row.allowClear || false;
      break;
    case 'Input':
      row.disabled = row.disabled || false;
      row.allowClear = row.allowClear || false;
      break;
    case 'Select':
      row.options = row.options || [];
      row.disabled = row.disabled || false;
      row.allowClear = row.allowClear || false;
      break;
  }
}

// 显示组件配置模态框
const showComponentConfigModal = (row) => {
  currentEditingRow.value = row;
  componentConfigModalVisible.value = true;
}

// 确认组件配置
const confirmComponentConfig = () => {
  componentConfigModalVisible.value = false;
  currentEditingRow.value = null;
}

// 取消组件配置
const cancelComponentConfig = () => {
  componentConfigModalVisible.value = false;
  currentEditingRow.value = null;
}
</script>

<style scoped>
.extracted-data-container {
  overflow-y: auto;
  padding: 15px;
}

:deep(.vxe-header--column) {
  font-weight: 500;
}

:deep(.vxe-table--header-wrapper) {
  font-weight: 500;
}
</style>